package com.fanrenqiji.modules.business.upload.web;

import com.aliyun.oss.OSSClient;
import com.fanrenqiji.common.config.GlobalSetting;
import com.fanrenqiji.common.utils.StringDateUtil;
import com.fanrenqiji.common.utils.StringUtils;
import com.fanrenqiji.entity.CourseEntity;
import com.fanrenqiji.entity.EventCaseEntity;
import com.fanrenqiji.modules.business.eventcase.dao.EventCaseDao;
import com.google.common.collect.Lists;
import org.apache.commons.io.FilenameUtils;
import org.dozer.DozerBeanMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Created by yanwt on 2017/2/28.
 */
@Controller
@RequestMapping("/upload")
public class UploadController {

    @Value("${oss.endpoint}")
    private String endpoint;
    @Value("${oss.accessKeyId}")
    private String accessKeyId;
    @Value("${oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${oss.bucketName}")
    private String bucketName;
    @Autowired
    private EventCaseDao eventCaseDao;
    @Autowired
    DozerBeanMapper beanMapper;

    private static String oldpic =null ;
    private static String newpic = null;
    /**
     * @return
     */
    @RequestMapping(value = "/file", method = RequestMethod.GET)
    public String file(ModelMap model) {
        return "upload";
    }


    /**
     * @return
     */
    @RequestMapping(value = "/file", method = RequestMethod.POST)
    @ResponseBody
    public String upload(MultipartHttpServletRequest request, String CKEditorFuncNum) {
        List<MultipartFile> files = request.getFiles("upload");
        System.out.println("aaaaa");
        String fileUrl = "";
        for (int i = 0; i < files.size(); i++) {
            MultipartFile file = files.get(i);
            if (!file.isEmpty()) {
                // 创建OSSClient实例
                OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
                // 上传文件流
                try {
                    String fileName = file.getOriginalFilename();
                    String fileSuffix = StringUtils.substring(fileName,
                            fileName.lastIndexOf(".") + 1);
                    String uri = "upload/" + StringDateUtil.getCurrentyyyyMMdd() + "/" + UUID.randomUUID() + "." + fileSuffix;
                    ossClient.putObject(bucketName, uri, file.getInputStream());
                    fileUrl = "http://data.fanrenqiji.com/" + uri;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                // 关闭client
                ossClient.shutdown();
            }
        }

        return "<script type=\"text/javascript\">" +
                "window.parent.CKEDITOR.tools.callFunction( " + CKEditorFuncNum + ",'" + fileUrl + "','');" +
                "</script>";
    }

    /**
     * 上传图片
     * @param pic
     * @param request
     * @param response
     * @throws IllegalStateException
     * @throws IOException
     */
    @RequestMapping(value = "uploadPic")
    @ResponseBody
    public String uploadPic(MultipartFile pic,HttpServletRequest request, HttpServletResponse response) throws IllegalStateException, IOException{
        String filename = pic.getOriginalFilename();
        String suffix = FilenameUtils.getExtension(filename);
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String newName = uuid + "." + suffix;
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        System.out.println("12312");
        String uri = "upload/" + StringDateUtil.getCurrentyyyyMMdd() + "/" + UUID.randomUUID() + "." + suffix;
        ossClient.putObject(bucketName, uri, pic.getInputStream());
        String fileUrl = "http://data.fanrenqiji.com/" + uri;
       //先进行贝蒂的处理 需要的是本地的文件夹
       return  fileUrl;
    }

    /**
     * 上传音频
     * @param vidio
     * @param request
     * @param response
     * @throws IllegalStateException
     * @throws IOException
     */
    @RequestMapping(value = "uploadVidio")
    @ResponseBody
    public String uploadVidio( MultipartFile vidio, HttpServletRequest request, HttpServletResponse response)throws IllegalStateException, IOException{
        // 1、文件改名
            String filename = vidio.getOriginalFilename();
            String suffix = FilenameUtils.getExtension(filename);
            String uuid = UUID.randomUUID().toString().replace("-", "");
            String newName = uuid + "." + suffix;
        // 2、文件上传
        System.out.println();
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        String uri = "upload/" + StringDateUtil.getCurrentyyyyMMdd() + "/" + UUID.randomUUID() + "." + suffix;
        ossClient.putObject(bucketName, uri, vidio.getInputStream());
        String fileUrl = "http://data.fanrenqiji.com/" + uri;
        return fileUrl;

    }
    /**
     * 备课页面上传图片
     * @param pics
     * @param request
     * @param response
     * @throws IllegalStateException
     * @throws IOException
     */
    @RequestMapping(value = "uploadPic2")
    @ResponseBody
    public List<String> uploadPic2(@RequestParam MultipartFile[] pics,HttpServletRequest request, HttpServletResponse response) throws IllegalStateException, IOException{
        ArrayList<String> urls = Lists.newArrayList();
        for (MultipartFile pic : pics) {
            String filename = pic.getOriginalFilename();
            String suffix = FilenameUtils.getExtension(filename);
            String uuid = UUID.randomUUID().toString().replace("-", "");
            String newName = uuid + "." + suffix;
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            String uri = "upload/" + StringDateUtil.getCurrentyyyyMMdd() + "/" + UUID.randomUUID() + "." + suffix;
            ossClient.putObject(bucketName, uri, pic.getInputStream());
            String fileUrl = "http://data.fanrenqiji.com/" + uri;
            urls.add(fileUrl);
        }
        return urls;
    }
    /**
     * 上传音频2
     * @param vidio
     * @param request
     * @param response
     * @throws IllegalStateException
     * @throws IOException
     */
    @RequestMapping(value = "uploadVidio2")
    @ResponseBody
    public String uploadVidio2( MultipartFile vidio, HttpServletRequest request, HttpServletResponse response)throws IllegalStateException, IOException{
        // 1、文件改名
        String filename = vidio.getOriginalFilename();
        String suffix = FilenameUtils.getExtension(filename);
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String newName = uuid + "." + suffix;
        // 2、文件上传
        System.out.println("11111");
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        String uri = "upload/" + StringDateUtil.getCurrentyyyyMMdd() + "/" + UUID.randomUUID() + "." + suffix;
        ossClient.putObject(bucketName, uri, vidio.getInputStream());
        String fileUrl = "http://data.fanrenqiji.com/" + uri;
        return fileUrl;

    }

    /**
     * 作业文件的上传
     * @param taskfiles
     * @return
     * @throws IllegalStateException
     * @throws IOException
     */
    @RequestMapping(value = "uploadtaskfile")
    @ResponseBody
    public String uploadtaskfile(MultipartFile taskfiles)throws IllegalStateException, IOException{
        // 1、文件改名
        System.out.println(12);
        String filename = taskfiles.getOriginalFilename();
        String suffix = FilenameUtils.getExtension(filename);
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String newName = uuid + "." + suffix;
        // 2、文件上传
        // 2、文件上传
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        String uri = "upload/" + StringDateUtil.getCurrentyyyyMMdd() + "/" + UUID.randomUUID() + "." + suffix;
        ossClient.putObject(bucketName, uri, taskfiles.getInputStream());
        String fileUrl = "http://data.fanrenqiji.com/" + uri;
        return fileUrl;
    }

    /**
     * 答案文件的上传
     * @param answerfile
     * @return
     * @throws IllegalStateException
     * @throws IOException
     */
    @RequestMapping(value = "uploadanswerfile")
    @ResponseBody
    public String uploadanswerfile(MultipartFile answerfile,MultipartHttpServletRequest request, String CKEditorFuncNum)throws IllegalStateException, IOException{
        // 1、文件改名
        String filename = answerfile.getOriginalFilename();
        String suffix = FilenameUtils.getExtension(filename);
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String newName = uuid + "." + suffix;
        // 2、文件上传
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        String uri = "upload/" + StringDateUtil.getCurrentyyyyMMdd() + "/" + UUID.randomUUID() + "." + suffix;
        ossClient.putObject(bucketName, uri, answerfile.getInputStream());
        String fileUrl = "http://data.fanrenqiji.com/" + uri;
        return fileUrl;

    }

    /**
     * 答案文件的上传2
     * @param answerfiles
     * @return
     * @throws IllegalStateException
     * @throws IOException
     */
    @RequestMapping(value = "uploadanswerfile2")
    public String uploadanswerfile2(MultipartFile answerfiles,MultipartHttpServletRequest request, String CKEditorFuncNum,String eventcaseid,String courseid)throws IllegalStateException, IOException{
        // 1、文件改名
        String filename = answerfiles.getOriginalFilename();
        String suffix = FilenameUtils.getExtension(filename);
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String newName = uuid + "." + suffix;
        // 2、文件上传
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        String uri = "upload/" + StringDateUtil.getCurrentyyyyMMdd() + "/" + UUID.randomUUID() + "." + suffix;
        ossClient.putObject(bucketName, uri, answerfiles.getInputStream());
        String fileUrl = "http://data.fanrenqiji.com/" + uri;
        //接下来就是获取到事件实例对象 然后将文件的路径进行保存
        EventCaseEntity eventCaseEntity = eventCaseDao.findOne(Long.parseLong(eventcaseid));
        /*eventCaseEntity.setAnswerFileUrl(fileUrl);*/
        eventCaseDao.save(eventCaseEntity);
        return "redirect:" + GlobalSetting.getAdminPath() + "/business/course/addeventcase?id="+courseid;
    }

    /**
     * 作业文件的上传2
     * @param taskfiles
     * @return
     * @throws IllegalStateException
     * @throws IOException
     */
    @RequestMapping(value = "uploadtaskfile2")
    public String uploadtaskfile2(MultipartFile taskfiles,MultipartHttpServletRequest request, String CKEditorFuncNum,String eventcaseid,String courseid)throws IllegalStateException, IOException{
        // 1、文件改名
        String filename = taskfiles.getOriginalFilename();
        String suffix = FilenameUtils.getExtension(filename);
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String newName = uuid + "." + suffix;
        // 2、文件上传
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        String uri = "upload/" + StringDateUtil.getCurrentyyyyMMdd() + "/" + UUID.randomUUID() + "." + suffix;
        ossClient.putObject(bucketName, uri, taskfiles.getInputStream());
        String fileUrl = "http://data.fanrenqiji.com/" + uri;
        //接下来就是获取到事件实例对象 然后将文件的路径进行保存
        EventCaseEntity eventCaseEntity = eventCaseDao.findOne(Long.parseLong(eventcaseid));
        CourseEntity courseEntity = new CourseEntity();
        eventCaseDao.save(eventCaseEntity);
        return "redirect:" + GlobalSetting.getAdminPath() + "/business/course/addeventcase?id="+courseid;
    }

}
